import { ref } from "vue";

export const useTheme = () => {
  const isDark = ref(false);
  const initTheme = () => {
    const theme = localStorage.getItem("theme") || "light";
    applyTheme(theme);
  };

  const toggleTheme = () => {
    const current = document.documentElement.getAttribute("data-theme");
    const theme = current === "dark" ? "light" : "dark";
    applyTheme(theme);
    localStorage.setItem("theme", theme);
  };

  const applyTheme = (theme: string) => {
    document.documentElement.setAttribute("data-theme", theme);
    isDark.value = theme === "dark";
    if (theme === "dark") {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
  };

  return {
    isDark,
    initTheme,
    toggleTheme,
  };
};
